<template>
  <view class="page">
    <u-navbar @leftClick="navLeftClick" class="u-m-b-12" :fixed="false" title="订单详情" placeholder bgColor="#fff"></u-navbar>
    <view class="status-info">
      <view class="u-flex">
        <image v-if="form.status == '0'" style="width: 32rpx;height: 32rpx;margin-right: 10rpx;" src="../../static/order/orderIcon1.png" />
        <image v-if="form.status == '1' || form.status == '6'" style="width: 32rpx;height: 32rpx;margin-right: 10rpx;" src="../../static/order/orderIcon2.png" />
        <image v-if="form.status == '2'" style="width: 32rpx;height: 32rpx;margin-right: 10rpx;" src="../../static/order/orderIcon3.png" />
        <view v-if="form.status == '0'" class="u-font-36 u-m-b-6">待支付</view>
        <view v-if="form.status == '1' || form.status == '6'" class="u-font-36 u-m-b-6">买家已付款</view>
        <view v-if="form.status == '2'" class="u-font-36 u-m-b-6">卖家已发货</view>
      </view>
      <view v-if="form.status == '0'" class="u-p-l-42 u-font-24" style="color: #E20300;">请在24小时内完成支付</view>
      <view v-if="form.status == '1' || form.status == '6'" class="u-p-l-42 u-font-24" style="color: #818181;">等待卖家发货</view>
      <view v-if="form.status == '2'" class="u-p-l-42 u-font-24" style="color: #818181;">还剩{{ form.sendGoodsTime || 7 }}天自动确认</view>
    </view>
    <view class="address">
      <view>
        <image style="width: 22rpx;height: 28rpx;margin-right: 14rpx;vertical-align: middle;" src="../../static/order/icon1.png" />
        <text class="u-font-28 u-m-b-6" style="font-weight: 600;color: #000000;">{{ form.province }}{{ form.city }}{{ form.district }}{{ form.adsDetail }}</text>
      </view>
      <view class="u-p-l-42 u-font-24" style="color: #333333;">{{ form.receiverName }} {{ form.receiverPhone }}</view>
    </view>
    <view class="order-list">
      <view class="u-m-b-32">
        <image style="width: 28rpx;height: 32.67rpx;margin-right: 10rpx;vertical-align: middle;" src="../../static/order/icon2.png" />
        <text class="u-font-28" style="font-weight: 600;color: #000000;">商品信息</text>
      </view>
      <view class="goods-list">
        <view v-for="(item, index) in list" :key="item.id">
          <view class="goods-item">
            <image class="goods-img" :src="item.subtitle?item.subtitle.split(',')[0]:''" mode="aspectFill" />
            <view class="u-flex-1 u-flex u-flex-column u-col-top u-row-between">
              <view class="u-line-2 u-font-24" style="color: #000;">{{ item.title }}</view>
              <view class="u-flex u-row-between" style="width: 100%;">
                <view class="u-font-24" style="color: #818181;">{{ item.skuName }}</view>
                <view class="u-font-28">x {{ item.quantity }}</view>
              </view>
            </view>
          </view>
          <view class="u-flex u-row-right u-m-t-12">
            <view class="btn1" v-if="form.status=='1' || form.status == '6'" @click="jumpTo('/pages/myOrder/refund', {id: id, outTradeNo: form.orderCode, tradeNo: form.transactionSerialNumber, orderItemsId: item.id})">申请退款</view>
          </view>
        </view>
      </view>
      <view class="u-flex u-row-between u-m-b-28 u-font-28">
        <view>商品总价</view>
        <view style="font-weight: 500;">¥ {{ (form.productAmountCents / 100).toFixed(2) }}</view>
      </view>
      <view class="u-flex u-row-between u-m-b-28 u-font-28">
        <view>配送方式</view>
        <view>快递配送</view>
      </view>
      <view class="u-flex u-row-between u-m-b-28 u-font-28">
        <view class="u-flex">
          <text class="u-m-r-8">快递费用</text>
          <image style="width: 20rpx;height: 20rpx;" src="../../static/order/doubt.png" />
        </view>
        <view style="font-weight: 500;">¥ {{ (form.shippingFeeCents / 100).toFixed(2) }}</view>
      </view>
      <view class="u-flex u-row-between u-m-b-30 u-font-28" v-if="form.remark">
        <view>备注</view>
        <view class="u-font-24" style="width: 458rpx;min-height: 64rpx;background-color: #F7F7F7;padding: 16rpx 10rpx;text-align: right;">{{ form.remark }}</view>
      </view>
      <u-line class="u-m-b-26" color="#E1E1E1"></u-line>
      <view class="u-font-28 u-text-right" style="font-weight: 500;">订单总价：<text class="u-font-32" style="color: #E20300;">¥ {{ (form.totalAmountCents / 100).toFixed(2) }}</text></view>
    </view>
    <view class="logistics" v-if="logisticsList.length">
      <view class="u-m-b-4">
        <image style="width: 28rpx;height: 25.66rpx;margin-right: 10rpx;vertical-align: middle;" src="../../static/order/icon4.png" />
        <text class="u-font-28" style="font-weight: 600;color: #000000;">发货信息</text>
      </view>
      <view class="u-flex u-row-between" v-for="item in logisticsList" :key="item.trackingNo">
        <view>
          <image style="width: 28rpx;height: 28rpx;margin-right: 10rpx;vertical-align: middle;" src="../../static/order/icon4.png" />
          <text class="u-font-24" style="color: #818181;">{{ getDictLable(item.carrier).lable }} {{ item.trackingNo }}</text>
        </view>
        <view class="u-font-24" style="color: #FF6600;" @click="jumpTo('/pages/myOrder/logistics', { orderId: form.id, carrier: getDictLable(item.carrier).value, trackingNo: item.trackingNo })">物流跟踪信息</view>
      </view>
    </view>
    <view class="order-info">
      <view class="u-font-28 u-m-b-16" style="color: #000000;">订单编号：{{ form.orderCode }}</view>
      <view class="u-font-28 u-m-b-16" style="color: #000000;">下单时间：{{ form.createdTime }}</view>
      <view class="u-font-28 u-m-b-16" v-if="form.status != '0' && form.status != '5'" style="color: #000000;">支付时间：{{ form.paidTime }}</view>
      <view class="u-font-28" v-if="form.status != '0' && form.status != '1' && form.status != '6' && form.status != '5'" style="color: #000000;">发货时间：{{ form.shippedTime }}</view>
    </view>
    <view class="bottom" :style="isFullSucreen? 'padding-bottom: 30px;' : '' ">
      <view class="bottom-content">
        <view class="btn1" v-if="form.status=='0'" @click="close">取消订单</view>
        <!-- <view class="btn1" v-if="form.status=='2'||form.status=='3'" @click="jumpTo('/pages/myOrder/logistics', {})">查看物流</view> -->
        <view class="btn2" v-if="form.status=='0'" @click="showPayType=true">继续支付</view>
        <view class="btn3" v-if="form.status=='2'" @click="confirm">确认收货</view>
      </view>
    </view>
    <u-popup :show="showPayResult" :round="20" mode="center" closeable @close="showPayResult=false">
      <view class="pay-result customize-popup">
        <view class="popup-title u-m-b-40">支付结果</view>
        <view class="u-text-center u-font-28 u-m-b-52">支付过程中是否有遇到问题？</view>
        <view class="btn-list">
          <view class="btn-item" style="color: #56CB03;background-color: #fff;" @click="getForm">取消支付</view>
          <view class="btn-item" style="color: #fff;background-color: #56CB03;" @click="getForm">我已完成支付</view>
        </view>
      </view>
		</u-popup>
    <payTypePopup :closePopup="() => showPayType=false" :showPayType="showPayType" :pay="pay" />
  </view>
</template>

<script>
import payTypePopup from '../../components/payTypePopup.vue'
import { getOrderForm, getOrderItemsList, closeOrder, confirmOrder, getOrderLogisticsInfo, aLiPay, wxPay, wxMiniAppPay } from '@/api/index'
import { getDicts } from '@/common/util'
import { isWeChatBrowser } from "@/common/util";

export default {
  components: {
    payTypePopup,
  },
  data() {
    return {
      isFullSucreen: this.isFullSucreen,
      showPayResult: false,
      showPayType: false,
      id: '',
      form: {},
      list: [],
      logistics: {},
      logisticsList: [],
      dict: {},
    };
  },
  onLoad(options) {
    getDicts(['logistics_status'], this)
    if(options.id) {
      this.id = options.id
    }
  },
  onShow() {
    if(this.id) {
      this.getForm()
    }
  },
  methods: {
    getDictLable(name) {
      const info = this.dict.logistics_status.find(v => v.value == name) || {}
      if(info.lable) {
        return info
      }
      return {}
    },
    close() {
      const that = this
      uni.showModal({
        title: '提示',
        content: '确定取消该笔订单?',
        showCancel: true,
        success: ({ confirm, cancel }) => {
          if(confirm) {
            closeOrder({ id: that.id }).then(res => {
              uni.showToast({
                icon: 'none',
                title: '订单取消成功'
              })
              setTimeout(() => {
                that.goBack()
              }, 1000)
            })
          }
        }
      })
    },
    confirm() {
      const that = this
      uni.showModal({
        title: '提示',
        content: '确定收到货物?',
        showCancel: true,
        success: ({ confirm, cancel }) => {
          if(confirm) {
            confirmOrder({ id: that.id }).then(res => {
              uni.showToast({
                icon: 'none',
                title: '收货成功'
              })
              that.getForm()
            })
          }
        }
      })
    },
    pay(e) {
      const that = this
      this.showPayType = false
      if(e == 'ali') {
        const parameter = {
          totalAmount: (+this.form.totalAmountCents / 100),
          payType: '2',
          outTradeNo: this.form.orderCode,
          subject: this.form.orderCode,
          deptId: uni.getStorageSync('userInfo').deptId,
        }
        const payUrl = `${window.location.origin}/pages/aliPay/aliPay?totalAmount=${parameter.totalAmount}&payType=${parameter.payType}&orderCode=${parameter.outTradeNo}&subject=${parameter.subject}&deptId=${parameter.deptId}&userId=${uni.getStorageSync('userInfo').userId}&userName=${uni.getStorageSync('userInfo').userName}&phonenumber=${uni.getStorageSync('userInfo').phonenumber}`
        uni.setClipboardData({
          data: payUrl,
          success: function () {
            uni.showModal({
              title: '提示',
              content: '复制成功,请使用系统浏览器支付.',
              showCancel: false,
              success: function (res) {
                that.showPayResult=true
              }
            });
          },
        });
        // aLiPay(parameter).then(res => {
        //   document.write(res.msg)
        // })
      } else if(e == 'wechat') {
        // 判断是否是微信浏览器
        if (isWeChatBrowser() && uni.getStorageSync('userInfo').openId) {
          uni.showLoading({ mask: true })
          wxMiniAppPay({ openId: uni.getStorageSync('userInfo').openId, payType: '2', orderCode: this.form.orderCode, totalAmount: +this.form.totalAmountCents}).then((res) => {
            uni.hideLoading()
            const data = JSON.parse(res.data.payParams)
            const { appId, nonceStr, paySign, signType, timeStamp } = data
            let payParams = {
              appId: appId,
              timeStamp: timeStamp,
              nonceStr: nonceStr,
              package: data.package,
              signType: signType,
              paySign: paySign,
            }
            WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, (res) => {
              this.showPayResult=true
              if (res.err_msg === 'get_brand_wcpay_request:ok') {
                uni.showToast({
                  icon: 'none',
                  title: `支付成功`
                })
              } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
                uni.showToast({
                  icon: 'none',
                  title: `取消支付`
                })
              } else {
                uni.showToast({
                  icon: 'none',
                  title: `支付失败`
                })
              }
            })
          })
        } else {
          uni.showToast({
            icon: 'none',
            title: `h5支付暂未开通`
          })
          // wxPay({})
        }

      } 
    },
    async getForm() {
      this.showPayResult = false
      uni.showLoading({ mask: true })
      await getOrderForm({id: this.id}).then(res => {
        this.form = res.data
        if(this.form.shippedTime && this.form.status == '2') {
          const now = new Date();
          const targetDate = new Date(this.form.shippedTime);
          const millisecondsPerDay = 1000 * 60 * 60 * 24;
          const timeDiff = targetDate.getTime() + 7 * millisecondsPerDay - now.getTime();
          const daysDiff = Math.floor(timeDiff / millisecondsPerDay);
          const hoursDiff = Math.floor((timeDiff % millisecondsPerDay) / (1000 * 60 * 60));
          const remainingTime = `${daysDiff}天 ${hoursDiff}小时`;
          this.form.sendGoodsTime = remainingTime
        }
      }).catch(() => {
        uni.hideLoading()
      })
      await getOrderItemsList({orderId: this.id, pageSize: 100}).then(res => {
        if(this.form.status == '5') {
          this.list = res.rows
          return
        }
        this.list = res.rows.filter(v => v.status == '1' || v.status == '6').map(v => {
          v.quantity = v.quantity - v.returnQuantity
          return v
        })
      }).catch(() => {
        uni.hideLoading()
      })
      await getOrderLogisticsInfo({orderId: this.id}).then(res => {
        this.logisticsList = res.rows || []
      }).catch(() => {
        uni.hideLoading()
      })
      uni.hideLoading()
    }
  },
};
</script>

<style lang="scss" scoped>
.page {
  width: 750rpx;
  min-height: 100vh;
  background-color: #F5F5F5;
  padding-bottom: 180rpx;
  position: relative;
  .status-info {
    width: 702rpx;
    margin: 0 auto;
    padding: 22rpx 0 16rpx;
  }
  .address {
    width: 702rpx;
    margin: 0 auto;
    padding: 26rpx;
    background: #FFFFFF;
    border-radius: 12rpx;
    margin-bottom: 12rpx;
  }
  .order-list {
    width: 702rpx;
    margin: 0 auto;
    padding: 24rpx 22rpx;
    background: #FFFFFF;
    border-radius: 12rpx;
    margin-bottom: 12rpx;
    .goods-list {
      display: flex;
      flex-direction: column;
      gap: 40rpx;
      margin-bottom: 40rpx;
      .goods-item {
        display: flex;
        gap: 20rpx;
        .goods-img {
          width: 140rpx;
          height: 140rpx;
          border-radius: 4rpx;
        }
      }
      .btn1 {
        width: 160rpx;
        height: 60rpx;
        line-height: 56rpx;
        text-align: center;
        background: #fff;
        border: 2rpx solid #000000;
        border-radius: 200rpx;
        font-size: 28rpx;
        color: #000000;
      }
    }
  }
  .logistics {
    width: 702rpx;
    background: #FFFFFF;
    border-radius: 12rpx;
    padding: 26rpx 22rpx;
    margin: 0 auto;
    margin-bottom: 12rpx;
  }
  .order-info {
    width: 702rpx;
    background: #FFFFFF;
    border-radius: 12rpx;
    padding: 32rpx 22rpx;
    margin: 0 auto;
  }
  .bottom {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    background: #FFFFFF;
    .bottom-content {
      width: 100%;
      background: #FFFFFF;
      padding: 20rpx 24rpx;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      gap: 12rpx;
      .btn1 {
        width: 160rpx;
        height: 60rpx;
        line-height: 56rpx;
        text-align: center;
        background: #fff;
        border: 2rpx solid #000000;
        border-radius: 200rpx;
        font-size: 28rpx;
        color: #000000;
      }
      .btn2 {
        width: 160rpx;
        height: 60rpx;
        line-height: 56rpx;
        text-align: center;
        background: #fff;
        border: 2rpx solid #56CB03;
        border-radius: 200rpx;
        font-size: 28rpx;
        color: #56CB03;
      }
      .btn3 {
        width: 160rpx;
        height: 60rpx;
        line-height: 56rpx;
        text-align: center;
        background: #56CB03;
        border: 2rpx solid #56CB03;
        border-radius: 200rpx;
        font-size: 28rpx;
        color: #fff;
      }
    }
  }
}

.pay-result {
  width: 632rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding-top: 60rpx;
  padding: 60rpx 24rpx 28rpx;
  
  .btn-list {
    display: flex;
    gap: 24rpx;
    .btn-item {
      flex: 1;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 2rpx solid #56CB03;
      background-color: #FCDDBA;
      font-size: 28rpx;
      border-radius: 200rpx;
    }
  }
}
</style>
